package com.baizhi.cmfzdemo.util;

import com.baizhi.cmfzdemo.entity.CmfzGuru;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

/**
 * Created by 54433 on 2019/4/8.
 */
public class ClassUtil {
    //POI步骤
    public static void setPoi(List<?> list,String tableName) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //准备数据
        //Array 工具类 asList() 把数据转为几个  参数为可变长
        //List<String> list = Arrays.asList("上师编号", "上师姓名", "上师头像的路径", "上师法号", "上师的状态");

        //1,创建一个excle文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        //2.创建一张表
        HSSFSheet sheet = workbook.createSheet(tableName);

        //4.选择一个单元格
        for (int i = 0; i < list.size(); i++) {
            //3.选择一行
            HSSFRow row = sheet.createRow(i);
            //获取对象
            Object o = list.get(i);
            //创建单元格
            //通过反射
            //获取类对象
            Class<?> aClass = o.getClass();
            //获得属性数组
            Field[] fields = aClass.getDeclaredFields();
            //遍历数组
            for (int j = 0; j <fields.length ; j++) {
                //获取属性名
                String name = fields[j].getName();
                //拼接出来get方法名
                String getMethod = "get"+name.substring(0,1).toUpperCase()+name.substring(1);
                //调用get方法获取返回值
                Object invoke = aClass.getDeclaredMethod(getMethod, null).invoke(o, null);
                //创建单元格
                HSSFCell cell = row.createCell(j);
                //把方法返回值写入到单元格中
                if(invoke instanceof Date){
                    //根据实际业务需要添加
                }
                cell.setCellValue(invoke.toString());
            }
        }
        //7.保存
        workbook.write(new FileOutputStream(new File("E://"+tableName+".xls")));
    }
}


